using System;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.IO;
using System.Xml;

namespace Silvery.Loader
{
    /// <summary>
    /// 包下载和读取
    /// </summary>
    public class ZIPLoader : BaseLoader, IZIPLoader
    {
        public ZIPLoader()
        {
        }
        public ZIPLoader(Uri uri)
            : base(uri)
        {
        }
        /// <summary>
        /// 下载读取完成，并在此处理
        /// </summary>
        /// <param name="stream"></param>
        protected override void LoadCompleted(IResStream stream)
        {
            base.LoadCompleted(stream);
            zipResourceInfo = new StreamResourceInfo(stream.ResouceStream, null);
        }
        private StreamResourceInfo zipResourceInfo = null;
        /// <summary>
        /// 从包里获得一张图片
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public BitmapImage GetImageFormZipPack(string filename)
        {
            BitmapImage tempBitmap =null;
            StreamResourceInfo imageResourceInfo = Application.GetResourceStream(zipResourceInfo, new Uri(@filename, UriKind.Relative));
            if (imageResourceInfo != null)
            {
                tempBitmap = new BitmapImage();
                tempBitmap.SetSource(imageResourceInfo.Stream);
                imageResourceInfo.Stream.Close();
            }
            return tempBitmap;
        }
        /// <summary>
        /// 从包里获得一段文本流
        /// </summary>
        /// <param name="Filename"></param>
        /// <returns></returns>
        public Stream GetTextStreamFormZipPack(string Filename)
        {
            if (zipResourceInfo == null)
                return null;
            StreamResourceInfo imageResourceInfo = Application.GetResourceStream(zipResourceInfo, new Uri(@Filename, UriKind.Relative));
            if (imageResourceInfo == null)
                return null;
            else
                return imageResourceInfo.Stream;
        }
        /// <summary>
        /// 从包里获得一个XML
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public XmlReader GetXmlReaderFromZipPack(string filename)
        {
            if (zipResourceInfo == null)
                return null;
            StreamResourceInfo imageResourceInfo = Application.GetResourceStream(zipResourceInfo, new Uri(@filename, UriKind.Relative));
            return XmlReader.Create(imageResourceInfo.Stream);
        }
        /// <summary>
        /// 销毁
        /// </summary>
        public override void Dispose()
        {
            zipResourceInfo.Stream.Close();
            zipResourceInfo = null;
            base.Dispose();
        }
    }
}
